package main.java.chessfootball.model.game;

import main.java.chessfootball.model.play.Move;
import main.java.chessfootball.model.play.Put;
import main.java.chessfootball.model.play.Turn;
import main.java.chessfootball.model.regulation.Match;
import main.java.chessfootball.model.regulation.Mode;
import main.java.chessfootball.model.regulation.Score;
import main.java.chessfootball.model.regulation.Time;
import main.java.chessfootball.model.rule.Rule;

/**
 * User: Igor
 * Date: 11.06.2011
 * Time: 7:35:38
 */
public class Game
{
	private Field field;
	private Match match;
	private Rule rule;

	public Game(Rule rule)
	{
		this.rule = rule;
		Side startSide = rule.getMatch().getStartSide();
		match = new Match(Mode.OUT_GAME,
				new Time(0, 0, rule.getMatch().getTimes().get(0).getPeriod(), startSide, startSide,
						rule.getMatch().getEndTurns(rule.getMatch().getTimes().get(0).getPeriod())), new Score(0, 0));
		field = new Field();
		field.start(rule.getMatch().getStartHalf(), startSide,
				rule.getMatch().getUniforms()[startSide.getId()],
				rule.getMatch().getPlayersCount(), rule.getMatch().getTimes().get(0).getPeriod());
	}

	public Game(Field field, Match match, Rule rule)
	{
		this.field = field;
		this.match = match;
		this.rule = rule;
	}

	public void move(Move move)
	{
		field.move(move);
		match.move();
	}

	public void put(Put put)
	{
		field.put(put);
	}

	public void turn()
	{
		switch (match.getMode())
		{
			case OUT_GAME:
			{
				if ((rule.getMatch().getPlayersCount() == field.getTeam(match.getTime().getTurnSide())
						.getPlayersCount())
						&& (rule.getMatch().getPlayersCount() == field
						.getTeam(match.getTime().getTurnSide().getInvert()).getPlayersCount()))
				{
					match.goInGame();
				}
				else
				{
					match.turnOutGame();
				}
			}
			break;
			case IN_GAME:
			{
				if (match.isEndOfTime(rule.getMatch(), field.getSideOfGoal()))
				{
					if (field.ballInGoal())
					{
						match.getScore().goal(field.getSideOfGoal());
					}
					match.nextPeriod(rule.getMatch());
					field.changeHalf();
					field.arrangement(match.getTime().getTurnSide(), match.getTime().getPeriod());
				}
				else if (field.ballInGoal())
				{
					match.goal(field.getSideOfGoal());
					field.arrangement(match.getTime().getTurnSide(), match.getTime().getPeriod());
				}
				else
				{
					match.turnInGame();
				}
			}
			break;
		}
	}

	public void turn(Turn turn)
	{
		for (Move move : turn.getMoves())
		{
			move(move);
		}
		turn();
	}

	public Field getField()
	{
		return field;
	}

	public Match getMatch()
	{
		return match;
	}

	public Rule getRule()
	{
		return rule;
	}

	@Override
	public String toString()
	{
		return match + "\r" + field;
	}
}
